'use strict';

(function(){
  function $all(s,root){ return Array.from((root||document).querySelectorAll(s)); }
  function isHex6(s){ return /^#[0-9a-fA-F]{6}$/.test(s||''); }
  function getHex(){
    const inp = $all('input[type="text"],input').find(i=>isHex6((i.value||'').trim()));
    if(inp) return inp.value.trim();
    const all = document.body.innerText||'';
    let m = all.match(/已选颜色[^#]*(#[0-9a-fA-F]{6})/); if(m) return m[1];
    m = all.match(/#[0-9a-fA-F]{6}/); if(m) return m[0];
    return '#27E6B8';
  }
  function parseRows(){
    function parse(el){
      const txt=el.textContent||'';
      const hex=((txt.match(/#[0-9a-fA-F]{3,6}/)||[])[0]||'').toUpperCase();
      const m = txt.match(/ΔE\s*([0-9.]+)/); const de=m?parseFloat(m[1]):999;
      let preview=null;
      for(const k of ['preview','audio','src','url']){ if(el.dataset && el.dataset[k]) preview=el.dataset[k]; }
      if(!preview){
        const p = el.querySelector('[data-preview],[data-audio],[data-src]'); if(p){
          for(const k of ['preview','audio','src']){ if(p.dataset && p.dataset[k]) preview=p.dataset[k]; }
          const href = p.getAttribute && p.getAttribute('href'); if(!preview && href && /\.(mp3|wav|ogg)$/i.test(href)) preview=href;
        }
      }
      const title=((el.querySelector('.title,.track-title,h3,h4,a,.name,.track-name')||el).textContent||'').trim().split('·')[0];
      return { title: title||'未知曲目', hex, deltaE: isFinite(de)?de:999, preview };
    }
    const rows = $all('li,.tile,.track,.row,.list-item,.item,.result,.result-item,.track-card,tr');
    const items = rows.map(parse).filter(x=>/^#[0-9A-F]{6}$/.test(x.hex) && isFinite(x.deltaE));
    const seen = new Set(); const out=[];
    for(const it of items){ const k=it.title+'|'+it.hex; if(!seen.has(k)){ seen.add(k); out.push(it);} }
    out.sort((a,b)=>a.deltaE-b.deltaE);
    return out.slice(0,500);
  }
  function toHsl(hex){
    const m=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex); if(!m) return null;
    const r=parseInt(m[1],16)/255,g=parseInt(m[2],16)/255,b=parseInt(m[3],16)/255;
    const max=Math.max(r,g,b),min=Math.min(r,g,b); let h,s,l=(max+min)/2;
    if(max===min){ h=0;s=0; } else { const d=max-min; s=l>0.5? d/(2-max-min): d/(max+min);
      switch(max){ case r: h=(g-b)/d+(g<b?6:0); break; case g: h=(b-r)/d+2; break; case b: h=(r-g)/d+4; break; } h*=60; }
    return {h,s,l};
  }
  function mapPreview(hex){
    const c=toHsl(hex)||{h:0,s:0,l:0.5}, h=c.h, s=c.s, l=c.l;
    if(s<0.10 || l<0.15 || l>0.85) return 'assets/previews/grey_minimal.wav';
    if(h>=-15 && h<15) return 'assets/previews/red_energy.wav';
    if(h>=15 && h<45) return 'assets/previews/orange_warm.wav';
    if(h>=45 && h<75) return 'assets/previews/yellow_bright.wav';
    if(h>=75 && h<150) return 'assets/previews/green_nature.wav';
    if(h>=150 && h<195) return 'assets/previews/teal_ambient.wav';
    if(h>=195 && h<255) return 'assets/previews/blue_calm.wav';
    if(h>=255 && h<285) return 'assets/previews/violet_serene.wav';
    if(h>=285 && h<330) return 'assets/previews/pink_romance.wav';
    return 'assets/previews/red_energy.wav';
  }
  function seed(hex){
    const d=[5,8,12,15,18,22,26,31,37,42];
    return d.map((v,i)=>({ title:'色彩匹配示例 '+(i+1), hex:hex.toUpperCase(), deltaE:v, preview: mapPreview(hex) }));
  }

  window.__rtGoColorSummary = function(){
    const hex = getHex().toUpperCase();
    const start = Date.now(); let last=-1, stableAt=Date.now();
    const timer = setInterval(()=>{
      const items=parseRows();
      if(items.length!==last){ last=items.length; stableAt=Date.now(); }
      const stable=(Date.now()-stableAt)>240;
      const timeout=(Date.now()-start)>1600;
      if((items.length>=1 && stable) || timeout){
        clearInterval(timer);
        const finalItems = items.length ? items : seed(hex);
        localStorage.setItem('rt_color_matches', JSON.stringify({ selectedHex: hex, generatedAt: Date.now(), items: finalItems }));
        if(window.renderColorResultsInline && document.getElementById('color-results-frame')){ try{ window.renderColorResultsInline(hex); }catch(e){} } else { location.href='color-results.html?hex=' + encodeURIComponent(hex); }
      }
    }, 80);
  };

  // 如果 overlay 提前设置了强制跳转标记，则立即执行
  if(localStorage.getItem('rt_force_go_color_summary') === '1'){
    localStorage.removeItem('rt_force_go_color_summary');
    try{ window.__rtGoColorSummary(); }catch(e){}
  }
})();
